package org.extremengine.shape;

import org.apache.commons.lang3.math.NumberUtils;
import org.extremengine.common.Point;


/**
 * 各边平行与x轴或y轴的平行四边形(AABB)。
 * @author yuxing
 *
 */
public class ParallelRectangle extends Shape{

	double x1;
	double x2;
	double y1;
	double y2;

	public ParallelRectangle(double x1, double x2, double y1, double y2) {
		super();
		this.x1 = x1;
		this.x2 = x2;
		this.y1 = y1;
		this.y2 = y2;
	}
	
	@Override
	public Point getBarycenter() {
		return new Point(x1 +  (x2 - x1)/2, y1 +  (y2 - y1)/2);
	}

	@Override
	public void transform(double deltax, double deltay) {
		x1 += deltax;
		x2 += deltax;
		y1 += deltay;
		y2 += deltay;
	}
	
	/**
	 * Wrap any supported shape to AABB
	 * @param shape
	 * @return
	 */
	public static ParallelRectangle wrap(Shape shape) {
		if(shape instanceof Circle) {
			Circle c = (Circle) shape;
			Point h = c.getHeart();
			double x1 = h.x - c.getRadius();
			double x2 = h.x + c.getRadius();
			double y1 = h.y - c.getRadius();
			double y2 = h.y + c.getRadius();
			return new ParallelRectangle(x1, x2, y1, y2);
		}
		else if (shape instanceof ParallelRectangle) {
			return (ParallelRectangle) shape;
		}
		else if (shape instanceof Rectangle) {
			Rectangle rec = (Rectangle) shape;
			return new ParallelRectangle(NumberUtils.min(rec.getXs()), NumberUtils.max(rec.getXs()),
					NumberUtils.min(rec.getYs()), NumberUtils.max(rec.getYs()));
		}
		else if (shape instanceof Polygon) {
			throw new RuntimeException("Not implemented yet");
		}
		return null;
	}

	/**
	 * 两个AABB在x轴或者y轴投影的相交距离，若相交，则返回值>=0，否则为-1
	 * @param target
	 * @param coordinateAxis X轴或者Y轴
	 * @return 
	 */
	public double projectionOverlap(ParallelRectangle target, int coordinateAxis) {
		if (coordinateAxis == COORDINATE_AXIS_X) {
			if (target.x1 > x1 && target.x1 < x2) {
				return x2 - target.x1;
			}
			else if (target.x2 > x1 && target.x2 < x2) {
				return target.x2 - x1;
			}
		}
		else if (coordinateAxis == COORDINATE_AXIS_Y) {
			if (target.y1 > y1 && target.y1 < y2) {
				return y2 - target.y1;
			}
			else if (target.y2 > y1 && target.y2 < y2) {
				return target.x2 - x1;
			}
		}
		return -1;
	}

	public double getX1() {
		return x1;
	}

	public void setX1(double x1) {
		this.x1 = x1;
	}

	public double getX2() {
		return x2;
	}

	public void setX2(double x2) {
		this.x2 = x2;
	}

	public double getY1() {
		return y1;
	}

	public void setY1(double y1) {
		this.y1 = y1;
	}

	public double getY2() {
		return y2;
	}

	public void setY2(double y2) {
		this.y2 = y2;
	}
	
	public double getWidth() {
		return this.x2 - this.x1;
	}

	public double getHeight() {
		return this.y2 - this.y1;
	}
	
	public double getDiagonalLength() {
		return Math.sqrt(getWidth() * getWidth() + getHeight() * getHeight());
	}

	@Override
	public String toString() {
		return "PRectangle[" + x1 + ", " + x2 + ", " + y1 + ", " + y2 + "]";
	}

	@Override
	public Shape clone() {
		return new ParallelRectangle(x1, x2, y1, y2);
	}

	
	
}
